//
//  HJAttributedString.m
//  KaiChat
//
//  Created by lx on 2024/3/20.
//

#import "HJAttributedStringFactory.h"
 
@interface HJAttributedStringFactory()

 
@property (nonatomic, strong) NSMutableParagraphStyle *paragraphStyle;
@property (nonatomic, assign, readonly) CGFloat lineHeight;

@end


@implementation HJAttributedStringFactory

- (HJAttributedStringFactory *)initWithString:(NSString *)string maxWidth:(CGFloat)maxWidth font:(UIFont *)font lineSpacing:(CGFloat)lineSpacing alignment:(NSTextAlignment)alignment {
    if (self = [super init]) {
        
        if (isEmptyString(string)) {
            return nil;
        }
        
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        if (lineSpacing <= 0) {
            [paragraphStyle setLineSpacing:0];
        } else {
            [paragraphStyle setLineSpacing:lineSpacing];
        }
        
        paragraphStyle.alignment = alignment;
        
        self -> _attributedString = [[NSAttributedString alloc] initWithString:string attributes:@{
            NSFontAttributeName: font,
            NSParagraphStyleAttributeName: paragraphStyle,
        }];
        
        CGSize textSize = [self.attributedString boundingRectWithSize:CGSizeMake(maxWidth, CGFLOAT_MAX) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil].size;
        textSize = CGSizeMake(ceil(textSize.width), ceil(textSize.height));
        self -> _lineHeight = font.lineHeight;
        self -> _numberOfLines = ceil((textSize.height - paragraphStyle.lineSpacing) / (self.lineHeight + paragraphStyle.lineSpacing));
        self -> _size = textSize;
        self.paragraphStyle = paragraphStyle;
    }
    return self;
}

- (NSString *)description {
    return [NSString stringWithFormat:@"_attributedString = %@, size = %@, _lineHeight = %ld, _numberOfLines = %ld", _attributedString.string, NSStringFromCGSize(_size), (long)_lineHeight, _numberOfLines];
}

- (CGFloat)numberLineHeight:(NSInteger)number {
    return self.lineHeight * number + (number - 1) * self.paragraphStyle.lineSpacing;
}

@end
